package com.farm.common.security;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.farm.kaiping.entity.FarmUser;
import lombok.experimental.UtilityClass;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * 安全工具类
 */
@UtilityClass
public class SecurityUtils {

    /**
     * 获取 Authentication
     */
    private Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     * 获取用户
     * @param authentication
     * @return FarmUser
     */
    public FarmUser getUser(Authentication authentication) {
        if (ObjectUtil.isEmpty(authentication.getPrincipal())){
            return null;
        }
        Object principal = authentication.getPrincipal();
        if (principal instanceof FarmUser) {
            return (FarmUser) principal;
        } else {
            return BeanUtil.toBean(principal, FarmUser.class);
        }
    }

    /**
     * 获取用户
     */
    public FarmUser getUser() {
        Authentication authentication = getAuthentication();
        return getUser(authentication);
    }

}
